<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @copyright   Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
/** @var $this \Magento\ConfigurableProduct\Block\Adminhtml\Product\Edit\Tab\Super\Config\Matrix */
?>
<?php
$variations = $this->getVariations();
if (!$variations) {
    return;
}
$usedProductAttributes = $this->getUsedAttributes();
$productByUsedAttributes = $this->getAssociatedProducts();
?>

<h3 class="title"><?php echo __('Current Variations'); ?></h3>

<div class="field">
    <div class="control">
        <table class="data-table">
            <thead>
                <tr>
                    <th class="col-display" data-column="display">
                        <?php echo __('Display'); ?>
                    </th>
                    <th class="col-image" data-column="image">
                        <?php echo __('Image'); ?>
                    </th>
                    <th class="col-name <?php echo $this->getAttributeFrontendClass('name'); ?>" data-column="name">
                        <?php echo __('Name'); ?>
                    </th>
                    <th class="col-sku <?php echo $this->getAttributeFrontendClass('sku'); ?>" data-column="sku">
                        <?php echo __('SKU'); ?>
                    </th>
                    <th class="col-price" data-column="price">
                        <?php echo __('Price'); ?>
                    </th>
                    <th class="col-qty" data-column="qty">
                        <?php echo __('Quantity'); ?>
                    </th>
                    <th class="col-weight <?php echo str_replace('required-entry', '', $this->getAttributeFrontendClass('weight')); ?>" data-column="weight">
                        <?php echo __('Weight'); ?>
                    </th>
                    <?php
                    foreach ($usedProductAttributes as $attribute) {
                        /** @var $attribute \Magento\Catalog\Model\Resource\Eav\Attribute */
                        echo '<th class="col-' . preg_replace('#[^a-z0-9]+#', '-', strtolower($attribute->getStoreLabel(0))) . '">', $attribute->getStoreLabel(0), '</th>', PHP_EOL;
                    }
                    ?>
                    <th class="col-actions hidden"></th>
                </tr>
            </thead>
            <tbody>
            <?php
            $isEven = true;
            $productPrice = (float)$this->getProduct()->getPrice();
            foreach ($variations as $variation) {
                $attributeValues = array();
                $attributeLabels = array();
                $attributeStoreLabels = array();
                $price = $productPrice;
                foreach ($usedProductAttributes as $attribute) {
                    /** @var $attribute \Magento\Catalog\Model\Resource\Eav\Attribute */

                    $attributeValues[$attribute->getAttributeCode()] = $variation[$attribute->getId()]['value'];
                    $attributeLabels[$attribute->getAttributeCode()] = $variation[$attribute->getId()]['label'];

                    if (isset($variation[$attribute->getId()]['price'])) {
                        $priceInfo = $variation[$attribute->getId()]['price'];
                        $price += ($priceInfo['is_percent'] ? $productPrice / 100.0 : 1.0) * $priceInfo['pricing_value'];
                    }
                }
                $attributeLabels = $this->escapeHtml($attributeLabels);
                $key = implode('-', $attributeValues);
                if (isset($productByUsedAttributes[$key])) {
                    $product = $productByUsedAttributes[$key];
                    ?>

                <tr data-role="row" class="<?php echo $isEven ? 'even' : '' ?>">
                    <td class="col-display" data-column="display">
                        <input type="checkbox" name="associated_product_ids[]" data-column="entity_id"
                               value="<?php echo $product->getId()?>" class="checkbox"
                               checked="checked"/>
                    </td>
                    <td class="col-image" data-column="image">
                        <?php $image = $product->getImage(); if ($image == 'no_selection'): $image = ''; endif; ;?>
                        <div class="action-upload<?php if ($image): ?> no-display<?php endif;?>" data-action="upload-image">
                            <span><?php echo __('Upload Image'); ?></span>
                            <input name="image" type="file" disabled="disabled" data-locked="1"
                                   data-url="<?php echo $this->escapeHtml($this->getImageUploadUrl()) ?>"
                                   title="<?php echo __('Upload Image'); ?>" />
                            <input id="product-<?php echo $product->getId()?>-variation-image"
                                   value="<?php echo $image?>" type="hidden"/>
                        </div>
                        <?php if ($image): ?>
                            <img src="<?php echo $this->helper('Magento\Catalog\Helper\Product')->getImageUrl($product)?>"
                                 class="variation" data-role="image"/>
                        <?php endif; ?>
                    </td>
                    <td class="col-name" data-column="name">
                        <a href="<?php echo $this->getEditProductUrl($product->getId())?>"
                           target="_blank"><?php echo $this->escapeHtml($product->getName())?></a>

                        <button type="button" data-action="choose" class="action-choose" title="<?php echo __('Choose'); ?>"
                                data-attributes="<?php echo $this->escapeHtml($this->helper('Magento\Core\Helper\Data')->jsonEncode($attributeValues)); ?>">
                            <span><?php echo __('Choose'); ?></span>
                        </button>
                    </td>
                    <td class="col-sku" data-column="sku">
                        <span data-column="sku"><?php echo $this->escapeHtml($product->getSku())?></span>
                    </td>
                    <td class="col-price" data-column="price">
                        <?php echo $this->renderPrice($price);?>
                    </td>
                    <td class="col-qty" data-column="qty"><?php echo $this->getProductStockQty($product->getId()) ?></td>
                    <td class="col-weight" data-column="weight"><?php echo $product->getWeight()?></td>
                    <?php
                    foreach ($usedProductAttributes as $attribute) {
                        /** @var $attribute \Magento\Catalog\Model\Resource\Eav\Attribute */
                        echo '<td class="col-' . preg_replace('#[^a-z0-9]+#', '-', strtolower($attribute->getStoreLabel())) . '">',
                            $this->escapeHtml($variation[$attribute->getId()]['label']), '</td>', PHP_EOL;
                    }
                    ?>
                    <td class="col-actions hidden" data-column="actions">
                        <div class="actions-split">
                            <button type="button" class="action-default">
                                <span>Edit</span>
                            </button>
                            <button type="button" class="action-toggle" data-toggle="dropdown">
                                <span>Select</span>
                            </button>
                            <ul class="dropdown-menu">
                                <li>
                                    <a class="item">Reset Variation</a>
                                </li>
                            </ul>
                        </div>
                    </td>
                </tr>
                    <?php
                } else {
                    $checked = $this->getProduct()->getId() && !$this->getProduct()->dataHasChangedFor('type_id') ? '' : ' checked="checked"';
                    $disabled = $this->getProduct()->getId() && !$this->getProduct()->dataHasChangedFor('type_id') ? ' disabled="disabled"' : '';
                    ?>
                <tr data-role="row" class="<?php echo $isEven ? 'even' : '' ?>">
                    <td class="col-display" data-column="display">
                        <input type="checkbox" name="associated_product_ids[]" value=""
                               class="checkbox" data-column="entity_id" <?php echo $checked?> />
                    </td>
                    <td class="col-image" data-column="image">
                        <div class="actions split actions-image-uploader">
                            <div class="action-upload action split" data-action="upload-image">
                                <span><?php echo __('Upload Image'); ?></span>
                                <input name="image" type="file" <?php echo $disabled;?>
                                       data-url="<?php echo $this->escapeHtml($this->getImageUploadUrl()) ?>"
                                       title="<?php echo __('Upload Image'); ?>" />
                                <input id="variations-matrix-<?php echo $key?>-image"
                                       name="variations-matrix[<?php echo $key?>][image]"
                                       type="hidden" <?php echo $disabled;?>/>
                            </div>
                            <button type="button" class="action toggle no-display" data-toggle="dropdown" data-mage-init='{"dropdown":{}}'>
                                <span><?php echo __('Select'); ?></span>
                            </button>
                            <ul class="dropdown">
                                <li>
                                    <a class="item" data-action="no-image"><?php echo __('No Image'); ?></a>
                                </li>
                            </ul>
                        </div>
                    </td>
                    <td class="col-name" data-column="name">
                        <input type="text"
                               id="variations-matrix-<?php echo $key?>-name"
                               name="variations-matrix[<?php echo $key?>][name]"
                               value="<?php echo $this->escapeHtml($this->getProduct()->getName()), '-', implode('-', $attributeLabels)?>"
                               class="<?php echo $this->getAttributeFrontendClass('name'); ?>"<?php echo $disabled?>/>
                        <input type="hidden" name="variations-matrix[<?php echo $key?>][configurable_attribute]"
                               value="<?php echo $this->escapeHtml($this->helper('Magento\Core\Helper\Data')->jsonEncode($attributeValues)); ?>"<?php echo $disabled?>/>

                        <button type="button" data-action="choose" class="action-choose" title="<?php echo __('Choose'); ?>"
                                data-attributes="<?php echo $this->escapeHtml($this->helper('Magento\Core\Helper\Data')->jsonEncode($attributeValues)); ?>"<?php echo $disabled;?>>
                            <span><?php echo __('Choose'); ?></span>
                        </button>
                    </td>
                    <td class="col-sku" data-column="sku">
                        <input type="text"
                               id="variations-matrix-<?php echo $key?>-sku"
                               name="variations-matrix[<?php echo $key?>][sku]"
                               value="<?php echo $this->escapeHtml($this->getProduct()->getSku()), '-', implode('-', $attributeLabels)?>"
                               class="<?php echo $this->getAttributeFrontendClass('sku'); ?>"<?php echo $disabled?>/>
                    </td>
                    <td class="col-price" data-column="price">
                        <?php echo $this->renderPrice($price) ?>
                    </td>
                    <td class="col-qty" data-column="qty">
                        <input type="text"
                               id="variations-matrix-<?php echo $key?>-qty"
                               name="variations-matrix[<?php echo $key?>][quantity_and_stock_status][qty]"
                               class="validate-number"
                               value=""<?php echo $disabled?>>
                    </td>
                    <td class="col-weight" data-column="weight">
                        <input type="text"
                               id="variations-matrix-<?php echo $key?>-weight"
                               name="variations-matrix[<?php echo $key?>][weight]"
                               class="<?php echo str_replace('required-entry', '', $this->getAttributeFrontendClass('weight')); ?>"
                               value="<?php echo $this->getProduct()->getWeight()?>"<?php echo $disabled?>>
                    </td>
                    <?php
                    foreach ($usedProductAttributes as $attribute) {
                        /** @var $attribute \Magento\Catalog\Model\Resource\Eav\Attribute */
                        echo '<td class="col-'
                            . preg_replace('#[^a-z0-9]+#', '-', strtolower($attribute->getStoreLabel())) . '">',
                            $this->escapeHtml($variation[$attribute->getId()]['label']),
                            '</td>', PHP_EOL;
                    }
                    ?>
                    <td class="col-actions hidden" data-column="actions">
                        <div class="actions-split">
                            <button type="button" class="action-default">
                                <span>Edit</span>
                            </button>
                            <button type="button" class="action-toggle" data-toggle="dropdown">
                                <span>Select</span>
                            </button>
                            <ul class="dropdown-menu">
                                <li>
                                    <a>Reset Variation</a>
                                </li>
                            </ul>
                        </div>
                    </td>
                </tr>
                    <?php
                }
                $isEven = !$isEven;
            }
            ?>
            </tbody>
        </table>
    </div>
</div>
<script data-template-for="variation-image" type="text/x-jquery-tmpl">
    <img src="${url}" class="variation" data-role="image"/>
</script>
<script type="text/javascript">
require([
    "jquery",
    "jquery/template",
    "jquery/file-uploader",
    "mage/mage",
    "mage/translate"
], function(jQuery){

jQuery(function ($) {
    var matrix = $('[data-role=product-variations-matrix]');
    matrix.find('[data-action=upload-image] [name=image]').each(function() {
        $(this).fileupload({
            dataType: 'json',
            dropZone: $(this).closest('[data-role=row]'),
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
            done: function (event, data) {
                if (!data.result) {
                    return;
                }
                if (!data.result.error) {
                    var parentElement = $(event.target).closest('[data-column=image]'),
                        uploaderControl = parentElement.find('[data-action=upload-image]'),
                        imageElement = parentElement.find('[data-role=image]');

                    if (imageElement.length) {
                        imageElement.attr('src', data.result.url);
                    } else {
                        $.tmpl(matrix.find('[data-template-for=variation-image]').html(), data.result)
                            .prependTo(uploaderControl);
                    }
                    parentElement.find('[name$="[image]"]').val(data.result.file);
                    parentElement.find('[data-toggle=dropdown]').show();
                } else {
                    alert($.mage.__('File extension not known or unsupported type.'));
                }
            },
            start: function(event) {
                $(event.target).closest('[data-action=upload-image]').addClass('loading');
            },
            stop: function(event) {
                $(event.target).closest('[data-action=upload-image]').removeClass('loading');
            }
        });
    });
    matrix.find('[data-action=no-image]').click(function (event) {
        var parentElement = $(event.target).closest('[data-column=image]');
        parentElement.find('[data-role=image]').remove();
        parentElement.find('[name$="[image]"]').val('');
        parentElement.find('[data-toggle=dropdown]').trigger('close.dropdown').hide();
    });
});

});
</script>
